package com.kawa.kemanage.controller;

import com.github.pagehelper.PageInfo;
import com.kawa.kemanage.entity.NewsDetail;
import com.kawa.kemanage.service.NewsService;
import com.kawa.kemanage.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @Author: KAIyo
 * @Date: 2025/6/3 0:29
 * @Version: v1.0.0
 * @Description: TODO
 **/
@RestController
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;





    /**@GetMapping("/list")
     * 根据类型，文章标题，发布时间,查询所有新闻
     * @return
     */
    @GetMapping("/list")
    public Result findAllNews(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false)  @DateTimeFormat(pattern = "yyyy-MM-dd")Date createDate,
            @RequestParam(required = false)  @DateTimeFormat(pattern = "yyyy-MM-dd")Date modifyDate
    ) {
        PageInfo<NewsDetail> allNews = newsService.findAllNews(pageNum, pageSize, categoryId, title, createDate, modifyDate);
        return Result.success(allNews);
    }







    /**@GetMapping("/list/{id}")
     * 根据id查询新闻
     * @param id
     * @return
     */
    @GetMapping("/list/{id}")
    public Result getNewsById(@PathVariable Long id) {
        NewsDetail newsDetail = newsService.getNewsById(id);
        if (newsDetail != null) {
            return Result.success(newsDetail);
        } else {
            return Result.error("新闻不存在");
        }
    }




    /**
     * @PostMapping("/add")
     * 新增新闻
     * @param newsDetail
     * @return
     *
     */
    @PostMapping("/add")
    public Result addNews(@RequestBody NewsDetail newsDetail) {
        newsDetail.setModifyDate(new Date());

        int result = newsService.addNews(newsDetail);
        if (result >0){
           return Result.success(result);
        }else{
           return Result.error(500,"发送失败");
        }
    }




    /**@PostMapping("/update/{id}")
     * 根据id修改新闻
     * @param news
     * @return
     */
    @PostMapping("/update/{id}")
    public Result updateNews(@PathVariable Integer id,@RequestBody NewsDetail news){
        news.setId(id);
        if(newsService.updateNewsById(news)){
            return Result.success(news);
        }else {
            return Result.error("修改失败");
        }
    }




    /** @PostMapping("/delete/{id}")
     * 根据id删除新闻
     * @param id
     * @return
     *
     * */
    @PostMapping("/delete/{id}")
    public Result delNews(@PathVariable Integer id){
        if (newsService.delNewsById(id)){
            return  Result.success(null);
        }else {
            return Result.error("删除失败");
        }
    }


}
